package com.devstringx.pmt.persitence.common;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CommonApplicationDAO{


	@Autowired(required=true)
	private SessionFactory sessionFactory;

	private Session currentSession;

	public List loadAllRows(Class entityToLoad){
		List result = new ArrayList();
		currentSession =  sessionFactory.openSession();
		Transaction transaction =  currentSession.beginTransaction();
		Criteria criteria = currentSession.createCriteria(entityToLoad);
		result = criteria.list();
		transaction.commit();
		//transaction = null;
		if(currentSession.isOpen())
			currentSession.close();
		currentSession = null;
		return result;
	}

	public void insertNewRow(Object entityToInsert){
		currentSession = sessionFactory.getCurrentSession();
		currentSession.save(entityToInsert);
	}

	public List loadAllRowsForCriteria(DetachedCriteria criteria){
		List result = null;
		currentSession = sessionFactory.getCurrentSession();
		result = criteria.getExecutableCriteria(currentSession).list();
		return result;
	}
	
	public List loadAllRowsForCriteriaOnStartUp(DetachedCriteria criteria){

		List result=null;
		Session session=sessionFactory.openSession();
		Transaction transaction=   session.beginTransaction();
		result= criteria.getExecutableCriteria(session).list();
		transaction.commit();
		if(session.isOpen()){
			session.close();
		}
		return result;
	}

	public void updateExistingRow(Object objectToUpdate){
		Session currentSession = sessionFactory.getCurrentSession();
		currentSession.saveOrUpdate(objectToUpdate);
	}

	public void updateExistingRowForMannualSession(Object objectToUpdate){
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		session.update(objectToUpdate);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public List loadAllRowsForCustomQuery(String query) {
		currentSession = sessionFactory.getCurrentSession();
		SQLQuery sqlQuery = currentSession.createSQLQuery(query);
		List list = sqlQuery.list();
		return list;
	}

	public List loadAllRowsForCustomQueryOnStartUp(String query){
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		SQLQuery sqlQuery = session.createSQLQuery(query);
		List list = sqlQuery.list();
		session.getTransaction().commit();
		return list;
	}
	
	public void evictFromSession(Object objectToEvict){
		sessionFactory.getCurrentSession().evict(objectToEvict);
	}
	
	public void deleteRow(Object objectToDelete){
		
		 sessionFactory.getCurrentSession().delete(objectToDelete);
	}

}
